package com.sanqing.iframe;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.*;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JFormattedTextField;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import com.sanqing.model.NumberListener;
import com.sanqing.model.BookInfo;
import com.sanqing.dao.Dao;
import com.sanqing.model.*;

public class BookModiAndDelIFrame extends JInternalFrame {
    private JTextField ISBN;
    private JComboBox bookType;
    private DefaultComboBoxModel bookTypeModel;
    private JTextField BookName;
    private JTextField Writer;
    private JTextField Publisher;
    private JTextField Translator;
    private JTextField Language; // 新增：语言文本框
    private JFormattedTextField number; // 库存数量字段
    private JFormattedTextField PubDate;
    private JFormattedTextField Price;
    private String[] columnNames;
    private JTable table;
    private Item item;
//    private String OldISBN;
    private Map<Integer, Item> IdToItem = new HashMap<>();
    private int OldNumber; // 保存原来的库存数量
    private boolean isNewRecord = false; // 标记是否为新增记录

    private Object[][] getFileStates(List list) {
        // 新增：在列名中添加"语言"
        String[] columnNames = { "图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "语言", "出版日期", "价格", "库存数量" };
        Object[][] results = new Object[list.size()][columnNames.length];
        for (int i = 0; i < list.size(); i++) {
            BookInfo bookinfo = (BookInfo) list.get(i);
            results[i][0] = bookinfo.getISBN();
            Integer typeId = bookinfo.getTypeid();
            String bookTypeName = MapPz.getIdToName().get(typeId);
            results[i][1] = bookTypeName;
            results[i][2] = bookinfo.getBookname();
            results[i][3] = bookinfo.getWriter();
            results[i][4] = bookinfo.getTranslator();
            results[i][5] = bookinfo.getPublisher();
            results[i][6] = bookinfo.getLanguage(); // 新增：获取语言信息
            results[i][7] = bookinfo.getDate();
            results[i][8] = bookinfo.getPrice();
            results[i][9] = bookinfo.getNumber(); // 添加库存数量到表格
        }
        return results;
    }

    public BookModiAndDelIFrame() {
        super();
        final BorderLayout borderLayout = new BorderLayout();
        getContentPane().setLayout(borderLayout);
        setIconifiable(true);
        setClosable(true);
        setTitle("图书信息修改");
        setBounds(20, 60, 850, 406); // 新增：调整窗体宽度以容纳新控件
        final JPanel mainPanel = new JPanel();
        final BorderLayout borderLayout_1 = new BorderLayout();
        borderLayout_1.setVgap(5);
        mainPanel.setLayout(borderLayout_1);
        mainPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
        getContentPane().add(mainPanel);
        final JScrollPane scrollPane = new JScrollPane();
        mainPanel.add(scrollPane);

        Object[][] results = getFileStates(Dao.selectBookInfo());
        // 新增：在列名中添加"语言"
        columnNames = new String[] { "图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "语言", "出版日期", "价格", "库存数量" };
        table = new JTable(results, columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 所有单元格都不可编辑
            }
        };
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.addMouseListener(new TableListener());
        scrollPane.setViewportView(table);

        final JPanel bookPanel = new JPanel();
        mainPanel.add(bookPanel, BorderLayout.SOUTH);
        final GridLayout gridLayout = new GridLayout(0, 6);
        gridLayout.setVgap(5);
        gridLayout.setHgap(5);
        bookPanel.setLayout(gridLayout);
        final JLabel ISBNLabel = new JLabel();
        ISBNLabel.setHorizontalAlignment(SwingConstants.CENTER);
        ISBNLabel.setText("书       号");
        bookPanel.add(ISBNLabel);
        ISBN = new JTextField(20);
        ISBN.setDocument(new MyDocument(13));
        ISBN.setEditable(false); // 设置ISBN文本框为不可编辑
        ISBN.setBackground(new Color(230, 230, 230)); // 设置浅灰色背景，提示用户不可编辑
        bookPanel.add(ISBN);
        final JLabel bookTypeLabel = new JLabel();
        bookTypeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        bookTypeLabel.setText("类       别");
        bookPanel.add(bookTypeLabel);
        bookType = new JComboBox();
        bookTypeModel = (DefaultComboBoxModel) bookType.getModel();
        List list = Dao.selectBookCategory();
        for (int i = 0; i < list.size(); i++) {
            BookType booktype = (BookType) list.get(i);
            item = new Item();
            item.setId(booktype.getId());
            item.setName((String) booktype.getTypeName());
            bookTypeModel.addElement(item);
            IdToItem.put(item.getId(), item);
            MapPz.getNameToId().put(item.getName(), item.getId());
        }
        bookPanel.add(bookType);
        final JLabel bookNameLabel = new JLabel();
        bookNameLabel.setHorizontalAlignment(SwingConstants.CENTER);
        bookNameLabel.setText("书     名");
        bookPanel.add(bookNameLabel);
        BookName = new JTextField(255);
        bookPanel.add(BookName);
        final JLabel writerLabel = new JLabel();
        writerLabel.setHorizontalAlignment(SwingConstants.CENTER);
        writerLabel.setText("作    者");
        bookPanel.add(writerLabel);
        Writer = new JTextField(50);
        bookPanel.add(Writer);
        final JLabel publisherLabel = new JLabel();
        publisherLabel.setHorizontalAlignment(SwingConstants.CENTER);
        publisherLabel.setText("出  版  社");
        bookPanel.add(publisherLabel);
        Publisher = new JTextField(20);
        bookPanel.add(Publisher);
        final JLabel translatorLabel = new JLabel();
        translatorLabel.setHorizontalAlignment(SwingConstants.CENTER);
        translatorLabel.setText("译      者");
        bookPanel.add(translatorLabel);
        Translator = new JTextField(50);
        bookPanel.add(Translator);
        
        // 新增：语言标签和文本框
        final JLabel languageLabel = new JLabel();
        languageLabel.setHorizontalAlignment(SwingConstants.CENTER);
        languageLabel.setText("语      言");
        bookPanel.add(languageLabel);
        Language = new JTextField(20);
        bookPanel.add(Language);
        
        final JLabel pubDateLabel = new JLabel();
        pubDateLabel.setHorizontalAlignment(SwingConstants.CENTER);
        pubDateLabel.setText("出 版 日 期");
        bookPanel.add(pubDateLabel);
        SimpleDateFormat myfmt = new SimpleDateFormat("yyyy-MM-dd");
        PubDate = new JFormattedTextField(myfmt.getDateInstance());
        PubDate.setValue(new java.util.Date());
        bookPanel.add(PubDate);
        
        final JLabel priceLabel = new JLabel();
        priceLabel.setHorizontalAlignment(SwingConstants.CENTER);
        priceLabel.setText("单      价");
        bookPanel.add(priceLabel);
        Price = new JFormattedTextField();
        Price.addKeyListener(new NumberListener());
        bookPanel.add(Price);
        
        final JLabel numberLabel = new JLabel();
        numberLabel.setHorizontalAlignment(SwingConstants.CENTER);
        numberLabel.setText("库      存");
        bookPanel.add(numberLabel);
        number = new JFormattedTextField();
        number.addKeyListener(new NumberListener());
        number.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                // 限制只能输入数字和退格键
                char c = e.getKeyChar();
                if (!(c >= '0' && c <= '9' || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE)) {
                    e.consume();
                }
            }
        });
        bookPanel.add(number);

        final JPanel bottomPanel = new JPanel();// 创建底部面板
        bottomPanel.setBorder(new LineBorder(new java.awt.Color(139, 137, 137), 1, false));// 设置边框
        getContentPane().add(bottomPanel, BorderLayout.SOUTH);// 添加到窗体底端

        final FlowLayout flowLayout = new FlowLayout();// 流布局管理器
        flowLayout.setVgap(2);// 设置组件之间垂直距离
        flowLayout.setHgap(30);// 设置组件之间平行距离
        flowLayout.setAlignment(FlowLayout.RIGHT);// 设置向右对齐
        bottomPanel.setLayout(flowLayout);// 设置底部面板布局

        final JButton updateButton = new JButton();// 创建修改按钮
        updateButton.addActionListener(new UpdateBookActionListener());// 注册监听器
        updateButton.setText("修改");// 设置按钮文本
        bottomPanel.add(updateButton);// 添加到底部面板
        
        final JButton deleteButton = new JButton();// 创建删除按钮
        deleteButton.addActionListener(new DeleteBookActionListener());// 注册监听器
        deleteButton.setText("删除");// 设置按钮文本
        bottomPanel.add(deleteButton);// 添加到底部面板
        
        final JButton closeButton = new JButton();// 创建关闭按钮
        closeButton.addActionListener(new ActionListener() {// 注册监听器
            public void actionPerformed(final ActionEvent e) {
                doDefaultCloseAction();// 关闭窗体
            }
        });
        closeButton.setText("关闭");// 设置按钮文本
        bottomPanel.add(closeButton);// 添加到底部面板
        final JLabel headLogo = new JLabel();// 图片标签
        ImageIcon bookModiAndDelIcon = new ImageIcon("res/login.jpg");// 图片图标
        headLogo.setIcon(bookModiAndDelIcon);// 设置标签显示图片
        headLogo.setOpaque(true);// 设置图片标签不透明
        headLogo.setBackground(new java.awt.Color(173, 216, 230));// 设置标签背景颜色
        headLogo.setPreferredSize(new Dimension(400, 80));// 设置标签的大小
        headLogo.setBorder(new LineBorder(new java.awt.Color(139, 137, 137), 1, false));// 设置标签边框
        getContentPane().add(headLogo, BorderLayout.NORTH);// 添加到窗体上端
        setVisible(true);// 显示窗体可见

        // 禁用ISBN文本框的键盘输入
        ISBN.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                e.consume(); // 消耗所有键盘事件
            }
        });
     // 新增：添加窗体焦点监听
        addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                refreshTable(); // 窗体获得焦点时刷新表格
            }
        });
    }

    public class TableListener extends MouseAdapter {
        public void mouseClicked(final MouseEvent e) {
            int selRow = table.getSelectedRow();
            if (selRow < 0)
                return;

            String isbns = table.getValueAt(selRow, 0).toString().trim();
//            OldISBN = isbns;   // 保存老的ISBN数据
            String typeName = table.getValueAt(selRow, 1).toString().trim();
            String bookNames = table.getValueAt(selRow, 2).toString().trim();
            String writers = table.getValueAt(selRow, 3).toString().trim();
            String translators = table.getValueAt(selRow, 4).toString().trim();
            String publishers = table.getValueAt(selRow, 5).toString().trim();
            String languages = table.getValueAt(selRow, 6).toString().trim(); // 新增：获取语言信息
            String dates = table.getValueAt(selRow, 7).toString().trim();
            String prices = table.getValueAt(selRow, 8).toString().trim();
            String nums = table.getValueAt(selRow, 9).toString().trim(); // 获取库存数量

            // 设置文本框值
            ISBN.setText(isbns);
            BookName.setText(bookNames);
            Writer.setText(writers);
            Translator.setText(translators);
            Publisher.setText(publishers);
            Language.setText(languages); // 新增：设置语言文本框
            PubDate.setText(dates);
            Price.setText(prices);
            number.setText(nums); // 设置库存数量
            OldNumber = Integer.parseInt(nums); // 保存原来的库存数量

            // 设置下拉框选中项
            for (int i = 0; i < bookTypeModel.getSize(); i++) {
                Item item = (Item) bookTypeModel.getElementAt(i);
                if (item.getName().equals(typeName)) {
                    bookType.setSelectedIndex(i);
                    return;
                }
            }
        }
    }

    public class DeleteBookActionListener implements ActionListener {
        public void actionPerformed(final ActionEvent e) {
            String isbn = ISBN.getText().trim();
            if (isbn.isEmpty()) {
                JOptionPane.showMessageDialog(null, "请先选择要删除的图书");
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(null, "确定要删除ISBN为 " + isbn + " 的图书吗？", 
                                                       "删除确认", JOptionPane.YES_NO_OPTION);
            if (confirm != JOptionPane.YES_OPTION) {
                return;
            }

            // 执行删除
            int t=Dao.selectBorrow("select * from tb_borrow where bookISBN='"+isbn+"' and isback=0").size();
            if(t>0)
            {
            	JOptionPane.showMessageDialog(null, "删除失败，该书有人借阅请检查数据");
            }
            else
            {
            	 int deleteResult = Dao.Deletebook(isbn);

                 if (deleteResult == 1) {
                     JOptionPane.showMessageDialog(null, "删除成功");
                     refreshTable();
                     clearFields(); // 清空表单
                 } else {
                     JOptionPane.showMessageDialog(null, "删除失败，该书有人借阅或预约请检查数据");
                 }
            }
           
        }
    }
    
    public class UpdateBookActionListener implements ActionListener {
        public void actionPerformed(final ActionEvent e) {
            // 基础数据校验
            String isbn = ISBN.getText().trim();
            if (isbn.isEmpty()) {
                JOptionPane.showMessageDialog(null, "请先选择要修改的图书");
                return;
            }
            if (BookName.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(null, "图书名称不能为空");
                return;
            }
            Item selectedItem = (Item) bookType.getSelectedItem();
            if (selectedItem == null) {
                JOptionPane.showMessageDialog(null, "请选择图书类别");
                return;
            }
            if (number.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(null, "库存数量不能为空");
                return;
            }
            
            // 新增：语言字段校验
            if (Language.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(null, "语言信息不能为空");
                return;
            }

            // 获取输入数据
            int typeId = selectedItem.getId();
            String bookname = BookName.getText().trim();
            String writer = Writer.getText().trim();
            String translator = Translator.getText().trim();
            String publisher = Publisher.getText().trim();
            String language = Language.getText().trim(); // 新增：获取语言信息
            Date date;
            try {
                date = Date.valueOf(PubDate.getText());
            } catch (IllegalArgumentException ex) {
                JOptionPane.showMessageDialog(null, "出版日期格式不正确，请使用yyyy-MM-dd格式");
                return;
            }
            double price;
            try {
                price = Double.parseDouble(Price.getText().trim());
                if (price <= 0) {
                    JOptionPane.showMessageDialog(null, "价格必须为正数");
                    return;
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "价格格式不正确，请输入数字");
                return;
            }
            
            int num;
            try {
                num = Integer.parseInt(number.getText().trim());
                if (num <= 0) {
                    JOptionPane.showMessageDialog(null, "库存数量必须为正整数");
                    return;
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "库存数量格式不正确，请输入整数");
                return;
            }

            // 执行更新，注意：这里假设Dao类的Updatebook方法已更新以支持language参数
            // 新增：添加language参数
//            int updateResult = Dao.Updatebook(OldISBN, isbn, typeId, bookname, writer, translator, publisher, date, price, num, language);
            int updateResult = Dao.Updatebook(isbn, typeId, bookname, writer, translator, publisher, language, date, price, num);
            if (updateResult == 1) {
                JOptionPane.showMessageDialog(null, "修改成功");
                refreshTable();
            } else {
                JOptionPane.showMessageDialog(null, "修改失败，请检查数据");
            }
        }
    }
    // 刷新表格数据
    private void refreshTable() {
        Object[][] results = getFileStates(Dao.selectBookInfo());
        DefaultTableModel model = new DefaultTableModel(results, columnNames);
        table.setModel(model);
    }
    private void clearFields() {
        // 清空普通文本框
        ISBN.setText("");
        BookName.setText("");
        Writer.setText("");
        Publisher.setText("");
        Translator.setText("");
        Language.setText(""); // 新增：清空语言文本框
        
        // 清空格式化文本框
        number.setText("");
        Price.setText("");
        
        // 清空日期字段
        PubDate.setValue(new java.util.Date()); // 重置为当前日期
        
        // 重置下拉框
        if (bookTypeModel.getSize() > 0) {
            bookType.setSelectedIndex(0);
        } else {
            bookType.setSelectedItem(null);
        }
        
        // 清空选中状态
        table.clearSelection();
        OldNumber = 0;
    }
    // 数字输入监听器，限制只能输入数字和小数点
    public class NumberListener extends KeyAdapter {
        @Override
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            JTextField source = (JTextField) e.getSource();
            
            // 允许数字、退格键、删除键和小数点
            if (!(c >= '0' && c <= '9' || c == KeyEvent.VK_BACK_SPACE || 
                  c == KeyEvent.VK_DELETE || c == '.')) {
                e.consume();
                return;
            }
            
            // 限制小数点数量（仅价格字段）
            if (source == Price && c == '.') {
                String text = source.getText();
                if (text.contains(".")) {
                    e.consume();
                }
            }
        }
    }
}